import React, { useEffect, useState } from 'react';
import { Select, ConfigProvider } from 'antd';
import type { IOption } from '../../type';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import 'moment/locale/zh-cn';
import styles from './index.less';

interface IProps {
  /**
   * 选择事件
   */
  onChange?: (values: { periodType?: string; periodDay?: string }) => void;

  /**
   * 选项
   */
  options: { label: string; value: string; children: IOption[] }[];
  /**
   * 选择值
   */
  value: {
    periodType: string;
    periodDay: string;
  };
}

const FrequencySelect = (props: IProps) => {
  const { onChange, value: _value, options = [] } = props;
  const [periodType, setPeriodType] = useState<string>();
  const [periodDay, setPeriodDay] = useState<string>();
  const [perioDayOption, setPerioDayOption] = useState<IOption[]>([]);

  useEffect(() => {
    if (_value) {
      setPeriodDay(_value.periodDay);
      setPeriodType(_value.periodType);
    }
  }, [_value]);

  const _onChange = (data: { periodType?: string; periodDay?: string }) => {
    onChange && onChange(data);
  };

  const onChangePeriodType = (e: string) => {
    const arr = options.find((item) => item.value === e);
    if (e !== periodType) {
      setPeriodDay(undefined);
    }
    setPeriodType(e);
    setPerioDayOption(arr?.children || []);
    const data = {
      periodType: e,
      periodDay,
    };
    _onChange(data);
  };

  const onChangePeriodDay = (e: string) => {
    setPeriodDay(e);
    const data = {
      periodType,
      periodDay: e,
    };
    _onChange(data);
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { label } = option;
    return label?.indexOf(input) >= 0;
  };

  return (
    <div className={styles.container}>
      <Select
        options={options}
        onChange={onChangePeriodType}
        placeholder="请选择"
        style={{ marginRight: 12 }}
      />
      <ConfigProvider locale={zh_CN}>
        <Select
          options={perioDayOption}
          onChange={onChangePeriodDay}
          showSearch={true}
          disabled={periodType === 'day'}
          placeholder="请选择"
          filterOption={filterOption as any}
        />
      </ConfigProvider>
    </div>
  );
};

export default FrequencySelect;
